#include "operationWindow.h"

#include <QMessageBox>

#include "ConstData.h"
#include "DeviceManager.h"
#include "System.h"
#include "define.h"
#include "ui_operationWindow.h"
const QString style_success = "QLabel{color: #00ad7c;}";
const QString style_fail = "QLabel{color: #d84a4a;}";
const QString style_normal = "QLabel{color: #b1cdd4;}";
operationWindow::operationWindow(QWidget *parent, QString deviceId, DisplayMode mode,
                                 bool isTimeSync)
    : QFrame(parent), m_deviceId(deviceId), m_displayMode(mode), ui(new Ui::operationWindow())
{
    ui->setupUi(this);
    this->setWindowTitle("设备控制");
    ui->label_title->setText(deviceId);
    ui->widget_2->setVisible(false);
    if (mode == DisplayMode::Popup) {
        this->setFixedSize(this->size());
        this->setWindowFlags(Qt::Window | Qt::WindowCloseButtonHint);
        this->setWindowModality(Qt::ApplicationModal);
    } else {
        this->setWindowFlags(Qt::Widget);
    }
    // 删除原有按钮
    for (auto it : ui->buttonGroup->buttons()) {
        ui->buttonGroup->removeButton(it);
        delete it;
    }
    auto helper = DeviceManager::instance()->getDeviceHelper(m_deviceId);
    if (helper) {
        connect(helper, &IDevice::commStatusChanged, this, &operationWindow::onCommStatusChanged);
        connect(helper, &IDevice::deviceDataChanged, this, &operationWindow::onDeviceDataChanged);
        int i = 0;
        for (const QString &text : helper->getOperateMap().keys()) {
            if (text == OperationNames::COMMON_SET_TIME) {
                continue;
            }
            QPushButton *button = new QPushButton(text, this);
            button->setFixedSize(75, 25);
            ui->buttonGroup->addButton(button, helper->getOperateMap().value(text, -1));
            ui->gridLayout->addWidget(button);
            i++;
        }
        if (i < 4) {
            QLabel *label = new QLabel("");
            label->setFixedSize(75, 10);
            ui->gridLayout->addWidget(label);  // 占位对齐
        }

        // 获取当前行数，在下一行添加垂直弹簧
        int currentRowCount = ui->gridLayout->rowCount();
        QSpacerItem *verticalSpacer =
            new QSpacerItem(20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding);
        ui->gridLayout->addItem(verticalSpacer, currentRowCount, 0);
        // 连接按钮点击事件
        connect(ui->buttonGroup, &QButtonGroup::idClicked, this,
                &operationWindow::handleParameterButtonClicked);

        // 是否显示校时按钮
        if (DEVICE_MAP[m_deviceId].isTimeSync) {
            ui->widget_2->setVisible(true);
            ui->buttonGroup->addButton(
                ui->pb_setTime, helper->getOperateMap().value(OperationNames::COMMON_SET_TIME, -1));
        }
    }
}

operationWindow::~operationWindow() { delete ui; }

void operationWindow::onCommStatusChanged(const bool &success)
{
    if (success) {
        ui->label_commStatus->setText("✅ 正常");
        ui->label_commStatus->setStyleSheet(style_success);
    } else {
        ui->label_commStatus->setText("❌ 失败");
        ui->label_commStatus->setStyleSheet(style_fail);
        ui->label_runStatus->setText("---");
        ui->label_deviceTime->setText("---");
    }
}
void operationWindow::onDeviceDataChanged(const DeviceData &deviceData)
{
    auto helper = DeviceManager::instance()->getDeviceHelper(m_deviceId);
    if (helper) {
        if (helper->getDeviceType() == DeviceType_ycl) {
            ui->label_runStatus->setText(helper->getStatusName(deviceData.ycl_step_state));
        } else {
            ui->label_runStatus->setText(helper->getStatusName(deviceData.status));
        }
        ui->label_deviceTime->setText(deviceData.datetime.toString("yyyy-MM-dd hh:mm:ss"));
    } else {
        ui->label_runStatus->setText("---");
        ui->label_deviceTime->setText("---");
    }
}
void operationWindow::handleParameterButtonClicked(int buttonId)
{
    // 通过ID获取按钮text
    QPushButton *button = qobject_cast<QPushButton *>(ui->buttonGroup->button(buttonId));
    if (!button) return;
    QString buttonText = button->text();
    // 通过text获取操作命令
    auto helper = DeviceManager::instance()->getDeviceHelper(m_deviceId);
    if (helper) {
        qint16 operateCode = helper->getOperateMap().value(buttonText, -1);
        if (operateCode == -1) {
            qDebug() << "Invalid operate code";
            return;
        }
        if (operateCode == helper->getOperateMap().value(OperationNames::COMMON_SET_TIME)) {
            helper->setDeviceTime(QDateTime::currentDateTime());
        } else {
            if (helper->isIdle() ||
                (operateCode == helper->getOperateMap().value(OperationNames::COMMON_STOP) ||
                 buttonText.contains("停止"))) {
                helper->control(operateCode);
                helper->startDataMonitoring();  // 手动读一次数据，避免数据更新不及时
            } else {
                showWarning(m_deviceId + " → " + "设备繁忙，请停止设备后再试");
            }
        }
    }
}
void operationWindow::showEvent(QShowEvent *event)
{
    QWidget::showEvent(event);
    auto helper = DeviceManager::instance()->getDeviceHelper(m_deviceId);
    if (helper && helper->isEnabled()) {
        this->setEnabled(true);
        ui->label_title->setText(m_deviceId);
    } else {
        this->setEnabled(false);
        ui->label_title->setText(m_deviceId + " (未启用)");
        ui->label_commStatus->setText("---");
        ui->label_commStatus->setStyleSheet(style_normal);
        ui->label_runStatus->setText("---");
        ui->label_deviceTime->setText("---");
    }
}
void operationWindow::hideEvent(QHideEvent *event)
{
    QWidget::hideEvent(event);
    auto system = System::instance();
    auto helper = DeviceManager::instance()->getDeviceHelper(m_deviceId);
    if (helper && !system->isRunning() && m_displayMode == DisplayMode::Embedded) {
        // helper->stopDataMonitoring();
    }
}
